package com.cc.mydlnademo

import android.os.Bundle
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import com.cc.dlnalib.DLNAController
import com.cc.dlnalib.DLNAUtil
import com.cc.dlnalib.isWifiConnected
import kotlinx.android.synthetic.main.list_item_video.view.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.cybergarage.upnp.Device

class VideoListFragment : Fragment() {
    var videoList = mutableListOf<VideoData>()
    lateinit var gridView: GridView
    lateinit var playViewModel: PlayViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        playViewModel = ViewModelProvider(
            activity!!,
            ViewModelProvider.NewInstanceFactory()
        ).get(PlayViewModel::class.java)
        gridView = GridView(context)
        val padding =
            TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                16F,
                resources.displayMetrics
            ).toInt()
        gridView.setPadding(padding, padding, padding, padding)
        gridView.verticalSpacing = padding
        gridView.horizontalSpacing = padding
        gridView.numColumns = 2
        return gridView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        GlobalScope.launch {
            val list = context?.getLocalVideo()
            videoList.clear()
            withContext(Dispatchers.Main) {
                list?.let {
                    videoList.addAll(it)
                    gridView.adapter = object : BaseAdapter() {
                        override fun getView(
                            position: Int,
                            convertView: View?,
                            parent: ViewGroup
                        ): View {
                            val itemView: View =
                                convertView
                                    ?: LayoutInflater.from(context)
                                        .inflate(R.layout.list_item_video, parent, false)
                            val videoData = getItem(position)
                            itemView.findViewById<TextView>(R.id.tvName)
                                .setText(videoData.title)
                            itemView.playingTip.visibility =
                                if (videoData.path == playViewModel.getCurrentPath()) View.VISIBLE else View.GONE
                            Glide.with(this@VideoListFragment)
                                .load(videoData.path)
                                .into(itemView.findViewById(R.id.ivCover))
                            return itemView
                        }

                        override fun getItem(position: Int): VideoData {
                            return it[position]
                        }

                        override fun getItemId(position: Int): Long {
                            return 0
                        }

                        override fun getCount(): Int {
                            return it.size
                        }
                    }
                    gridView.setOnItemClickListener { parent, view, position, id ->
                        if (!context!!.isWifiConnected()) {
                            Toast.makeText(context, "请连接WIFI", Toast.LENGTH_SHORT).show()
                            return@setOnItemClickListener
                        }
                        fun play(device: Device) {
                            playViewModel.deviceLiveData.value = device
                            playViewModel.videoListData.value = list
                            playViewModel.play(device, list[position]) {
                                Toast.makeText(context, "投屏成功", Toast.LENGTH_SHORT).show()
                                (activity as MainActivity).showPlaying()
                                (gridView.adapter as BaseAdapter).notifyDataSetChanged()
                            }
                        }
                        if (DLNAController.currentDevice == null) {
                            DLNAUtil.showDLNADialog(activity!!) { devide ->
                                play(devide)
                                null
                            }
                        } else {
                            playViewModel.deviceLiveData.value?.let {
                                play(it)
                            }
                        }
                    }
                    playViewModel.indexLiveData.observe(this@VideoListFragment, Observer {
                        GlobalScope.launch(Dispatchers.Main) {
                            (gridView.adapter as BaseAdapter).notifyDataSetChanged()
                        }
                    })
                }
            }
        }
    }
}
